package com.cart.controller;


import com.cart.models.Admin;
import com.cart.models.User;
import com.cart.pojo.Product;
import com.cart.services.OrderHistoryRepository;
import com.cart.services.ProductRepository;
import com.cart.services.UserRepository;

import java.util.List;
import java.util.Scanner;

public class AdminController {
    public static void adminActions(Admin admin, UserRepository userRepository, ProductRepository productRepository, OrderHistoryRepository orderHistoryRepository, Scanner scanner) {
        while (true) {
            System.out.println("管理员操作菜单：");
            System.out.println("1. 列出所有客户");
            System.out.println("2. 重置客户密码");
            System.out.println("3. 删除客户");
            System.out.println("4. 查询客户信息");
            System.out.println("5. 列出所有商品");
            System.out.println("6. 添加商品");
            System.out.println("7. 修改商品");
            System.out.println("8. 删除商品");
            System.out.println("9. 查询商品信息");
            System.out.println("10. 修改管理员密码");
            System.out.println("11. 退出管理员操作");
            System.out.print("请选择操作: ");
            int choice = scanner.nextInt();
            scanner.nextLine();  // 清理换行符

            switch (choice) {
                case 1:
                    listAllCustomers(userRepository);
                    break;
                case 2:
                    resetCustomerPassword(userRepository, scanner);
                    break;
                case 3:
                    deleteCustomer(userRepository, scanner);
                    break;
                case 4:
                    searchCustomerInfo(userRepository, scanner);
                    break;
                case 5:
                    listAllProducts(productRepository);
                    break;
                case 6:
                    addProduct(productRepository, scanner);
                    break;
                case 7:
                    modifyProduct(productRepository, scanner);
                    break;
                case 8:
                    deleteProduct(productRepository, scanner);
                    break;
                case 9:
                    searchProductInfo(productRepository, scanner);
                    break;
                case 10:
                    updateAdminPassword(admin, scanner);
                    break;
                case 11:
                    System.out.println("退出管理员操作");
                    return;
                default:
                    System.out.println("无效选择，请重试。");
            }
        }
    }

    private static void listAllCustomers(UserRepository userRepository) {
        List<User> customers = userRepository.findAllCustomers();
        for (User customer : customers) {
            System.out.println("ID: " + customer.getId() + ", 用户名: " + customer.getUsername() + ", 级别: " + customer.getUserLevel() +
                    ", 注册时间: " + customer.getRegistrationDate() + ", 累计消费: " + customer.getTotalSpent() +
                    ", 手机: " + customer.getPhone() + ", 邮箱: " + customer.getEmail());
        }
    }

    private static void resetCustomerPassword(UserRepository userRepository, Scanner scanner) {
        System.out.print("请输入客户ID: ");
        int customerId = scanner.nextInt();
        scanner.nextLine();
        String newPassword = "123456"; // 或者通过某种生成逻辑
        userRepository.updatePassword(customerId, newPassword);
        System.out.println("客户ID " + customerId + " 的密码已重置！");
    }

    private static void deleteCustomer(UserRepository userRepository, Scanner scanner) {
        System.out.print("请输入客户ID: ");
        int deleteCustomerId = scanner.nextInt();
        scanner.nextLine();
        System.out.print("删除客户前请确认，操作不可撤销，是否继续？(y/n): ");
        String confirm = scanner.nextLine();
        if (confirm.equalsIgnoreCase("y")) {
            userRepository.delete(deleteCustomerId);
            System.out.println("客户已删除！");
        } else {
            System.out.println("操作取消。");
        }
    }

    private static void searchCustomerInfo(UserRepository userRepository, Scanner scanner) {
        System.out.println("请输入要查询的方式：1. 客户ID  2. 客户用户名");
        int option = scanner.nextInt();
        scanner.nextLine();
        if (option == 1) {
            System.out.print("请输入客户ID: ");
            int customerId = scanner.nextInt();
            scanner.nextLine();
            User customer = userRepository.findById(customerId);
            if (customer != null) {
                System.out.println("ID: " + customer.getId() + ", 用户名: " + customer.getUsername() + ", 级别: " + customer.getUserLevel());
            } else {
                System.out.println("客户不存在！");
            }
        } else if (option == 2) {
            System.out.print("请输入客户用户名: ");
            String username = scanner.nextLine();
            User customer = userRepository.findByUsername(username);
            if (customer != null) {
                System.out.println("ID: " + customer.getId() + ", 用户名: " + customer.getUsername() + ", 级别: " + customer.getUserLevel());
            } else {
                System.out.println("客户不存在！");
            }
        } else {
            System.out.println("无效选择！");
        }
    }

    private static void listAllProducts(ProductRepository productRepository) {
        productRepository.findAll().forEach(product -> {
            System.out.println("编号: " + product.getId() + ", 名称: " + product.getName() + ", 生产厂家: " + product.getManufacturer() +
                    ", 生产日期: " + product.getProductionDate() + ", 型号: " + product.getModel() + ", 进货价: " + product.getPurchasePrice() +
                    ", 零售价: " + product.getRetailPrice() + ", 数量: " + product.getQuantity());
        });
    }

    private static void addProduct(ProductRepository productRepository, Scanner scanner) {
        System.out.println("添加商品");
        System.out.print("请输入商品ID: ");
        int id = scanner.nextInt();
        System.out.print("请输入商品名称: ");
        String name = scanner.nextLine();
        System.out.print("请输入生产厂家: ");
        String manufacturer = scanner.nextLine();
        System.out.print("请输入型号: ");
        String model = scanner.nextLine();
        System.out.print("请输入生产日期: ");
        String productionDate = scanner.nextLine();
        System.out.print("请输入进货价: ");
        double purchasePrice = scanner.nextDouble();
        System.out.print("请输入零售价: ");
        double retailPrice = scanner.nextDouble();
        System.out.print("请输入数量: ");
        int quantity = scanner.nextInt();
        scanner.nextLine();

        Product product = new Product(id, name, manufacturer, model, productionDate, purchasePrice, retailPrice, quantity);
        productRepository.save(product);
        System.out.println("商品已添加！");
    }

    private static void modifyProduct(ProductRepository productRepository, Scanner scanner) {
        System.out.print("请输入要修改的商品编号: ");
        int productId = scanner.nextInt();
        scanner.nextLine();
        Product product = productRepository.findById(productId);
        if (product != null) {
            System.out.print("请输入新的商品名称（当前: " + product.getName() + "）: ");
            String name = scanner.nextLine();
            System.out.print("请输入新的生产厂家（当前: " + product.getManufacturer() + "）: ");
            String manufacturer = scanner.nextLine();
            System.out.print("请输入新的型号（当前: " + product.getModel() + "）: ");
            String model = scanner.nextLine();
            System.out.print("请输入新的生产日期（当前: " + product.getProductionDate() + "）: ");
            String productionDate = scanner.nextLine();
            System.out.print("请输入新的进货价（当前: " + product.getPurchasePrice() + "）: ");
            double purchasePrice = scanner.nextDouble();
            System.out.print("请输入新的零售价（当前: " + product.getRetailPrice() + "）: ");
            double retailPrice = scanner.nextDouble();
            System.out.print("请输入新的数量（当前: " + product.getQuantity() + "）: ");
            int quantity = scanner.nextInt();
            scanner.nextLine();

            product.setName(name);
            product.setManufacturer(manufacturer);
            product.setModel(model);
            product.setProductionDate(productionDate);
            product.setPurchasePrice(purchasePrice);
            product.setRetailPrice(retailPrice);
            product.setQuantity(quantity);

            productRepository.update(product);
            System.out.println("商品信息已更新！");
        } else {
            System.out.println("商品不存在！");
        }
    }

    private static void deleteProduct(ProductRepository productRepository, Scanner scanner) {
        System.out.print("请输入商品ID: ");
        int productId = scanner.nextInt();
        scanner.nextLine();
        System.out.print("删除商品前请确认，操作不可撤销，是否继续？(y/n): ");
        String confirm = scanner.nextLine();
        if (confirm.equalsIgnoreCase("y")) {
            productRepository.delete(productId);
            System.out.println("商品已删除！");
        } else {
            System.out.println("操作取消。");
        }
    }

    private static void searchProductInfo(ProductRepository productRepository, Scanner scanner) {
        System.out.print("请输入要查询的方式：1. 商品名称  2. 生产厂家  3. 零售价格范围\n请选择: ");
        int option = scanner.nextInt();
        scanner.nextLine();
        if (option == 1) {
            System.out.print("请输入商品名称: ");
            String name = scanner.nextLine();
            productRepository.findAll().stream()
                    .filter(product -> product.getName().equalsIgnoreCase(name))
                    .forEach(product -> {
                        System.out.println("编号: " + product.getId() + ", 名称: " + product.getName() + ", 零售价: " + product.getRetailPrice());
                    });
        } else if (option == 2) {
            System.out.print("请输入生产厂家: ");
            String manufacturer = scanner.nextLine();
            productRepository.findAll().stream()
                    .filter(product -> product.getManufacturer().equalsIgnoreCase(manufacturer))
                    .forEach(product -> {
                        System.out.println(product);
                    });
        } else if (option == 3) {
            System.out.print("请输入最低零售价: ");
            double minPrice = scanner.nextDouble();
            System.out.print("请输入最高零售价: ");
            double maxPrice = scanner.nextDouble();
            scanner.nextLine();
            productRepository.findAll().stream()
                    .filter(product -> product.getRetailPrice() >= minPrice && product.getRetailPrice() <= maxPrice)
                    .forEach(product -> {
                        System.out.println(product);
                    });
        } else {
            System.out.println("无效选择！");
        }
    }

    private static void updateAdminPassword(Admin admin, Scanner scanner) {
        System.out.print("请输入旧密码: ");
        String oldPassword = scanner.nextLine();
        if (admin.getPassword().equals(admin.md5Hash(oldPassword))) {
            System.out.print("请输入新密码: ");
            String newPassword = scanner.nextLine();
            admin.updateAdminPassword(newPassword);
            System.out.println("管理员密码已更新！");
        } else {
            System.out.println("密码错误！");
        }
    }

}
